package com.yupi.yupicturebackend.controller;

import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import com.yupi.yupicturebackend.Exception.BusinessException;
import com.yupi.yupicturebackend.Exception.ErrorCode;
import com.yupi.yupicturebackend.annotation.AuthCheck;
import com.yupi.yupicturebackend.common.BaseResponse;
import com.yupi.yupicturebackend.common.ResultUtils;
import com.yupi.yupicturebackend.constant.UserConstant;
import com.yupi.yupicturebackend.manager.CosManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private CosManager cosManager;

    @PostMapping("/test/upload")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE) // 只有管理员才可上传
    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile multipartFile) {
        // 获取文件名
        String filename = multipartFile.getOriginalFilename();
        // 上传路径
        String filepath = String.format("/test/%s", filename);
        File file = null;
        try {
            // 创建临时文件
            file = File.createTempFile(filepath, null);
            // 填充临时文件
            multipartFile.transferTo(file);
            // 将临时文件上传到cos
            cosManager.putObject(filepath, file);
        } catch (Exception e) {
            log.error("upload error filepath = {}", filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            // 删除临时文件
            if (file != null) {
                boolean success = file.delete();
                if (!success) {
                    // 没有删除成功
                    log.error("delete temp file fail,filepath = {}", filepath);
                }
            }
        }
        // 返回文件路径
        return ResultUtils.success(filepath);
    }


    @GetMapping("/test/download")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public void testDownLoad(@RequestParam("filepath") String filepath, HttpServletResponse response) throws IOException {
        COSObjectInputStream objectContent = null;
        try {
            // 获取流
            COSObject cosobject = cosManager.getObject(filepath);
            objectContent = cosobject.getObjectContent();
            // 转字节数组
            byte[] byteArray = IOUtils.toByteArray(objectContent);
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filepath);
            // 写入响应
            response.getOutputStream().write(byteArray);
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("download error filepath = {}", filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        } finally {
            //  关闭流
            if (objectContent != null) {
                objectContent.close();
            }
        }
    }


}
